Vue Js Change Text of Div on Click: To change the text of a div element on click in Vue, you can utilize refs. Start by adding a ref attribute to the div element. Then, create a method in your Vue component that can access the ref using this.$refs and update the text content. Finally, bind this method to a click event in your HTML. When the button is clicked, the updateText function will execute and modify the text content of the div element with the ref “myDiv”.
How can I use Vue.js to change the text of a div element when a user clicks on it?
This code defines a Vue instance with an HTML template that includes a div with the text “This is my div” and a button labeled “Set Text”. When the button is clicked, the setText
method is called, which uses this.$refs
to access the myDiv
element and change its inner text to “New text for my div”.
Vue Js Change Text of Div on Click Example
<div id="app">
<div ref="myDiv">This is my div.</div>
<button @click="setText">Set Text</button>
</div>
<script>
new Vue({
el: '#app',
methods: {
setText() {
this.$refs.myDiv.innerText = "New text for my div.";
}
}
});
</script>